package com.app.couponsharelife.ui.view

import android.content.Context
import android.util.AttributeSet
import android.view.View
import android.widget.LinearLayout
import androidx.viewpager.widget.ViewPager
import com.app.couponsharelife.R
import com.app.couponsharelife.utils.AppUtils

/**
 * Created by guluwa on 2018/3/26.
 */
class BannerIndicator @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyle: Int = 0) :
        LinearLayout(context, attrs, defStyle) {

    private var currentItem = 0

    private var count = 0

    fun initIndicator(count: Int) {
        removeAllViews()
        this.count = count
        for (i in 0 until count) {
            val view = View(context)
            if (i == 0)
                view.setBackgroundResource(R.drawable.banner_select_circle_bg)
            else
                view.setBackgroundResource(R.drawable.banner_no_select_circle_bg)
            val layoutParams = LayoutParams(AppUtils.dip2px(context, 8f), AppUtils.dip2px(context, 8f))
            if (i != count - 1)
                layoutParams.rightMargin = AppUtils.dip2px(context, 8f)
            view.layoutParams = layoutParams
            addView(view)
        }
    }

    fun bindViewPager(bannerView: BannerView) {
        bannerView.bindListener(object : ViewPager.OnPageChangeListener {
            override fun onPageScrollStateChanged(state: Int) {
            }

            override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {
            }

            override fun onPageSelected(position: Int) {
                if (currentItem != position - 1) {
                    if (getChildAt(currentItem) != null)
                        getChildAt(currentItem).setBackgroundResource(R.drawable.banner_no_select_circle_bg)
                    currentItem = when (position) {
                        count + 1 -> 0
                        0 -> count - 1
                        else -> position - 1
                    }
                    if (getChildAt(currentItem) != null)
                        getChildAt(currentItem).setBackgroundResource(R.drawable.banner_select_circle_bg)
                }
            }
        })
    }
}